from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session, joinedload
from app.database import get_db
from app.models.order import Order
from app.models.spot import Spot
from app.core.auth import get_current_user
from datetime import datetime, timedelta
from typing import Optional
from pytz import timezone

router = APIRouter()

@router.get("")
def get_orders(
    db: Session = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """获取用户的所有订单"""
    orders = (
        db.query(Order)
        .filter(Order.user_id == current_user.id)
        .join(Spot)
        .options(joinedload(Order.spot))
        .order_by(Order.created_at.desc())
        .all()
    )
    
    # 转换为北京时间
    beijing_tz = timezone('Asia/Shanghai')
    
    def format_datetime(dt):
        if dt:
            # 如果时间没有时区信息，假定为本地时间
            if dt.tzinfo is None:
                beijing_tz = timezone('Asia/Shanghai')
                dt = beijing_tz.localize(dt)
            # 确保时间是北京时间
            beijing_time = dt.astimezone(timezone('Asia/Shanghai'))
            # 返回格式化的时间字符串
            return beijing_time.strftime('%Y-%m-%d %H:%M:%S')
        return None
    
    # 转换为字典并包含景点信息
    result = []
    for order in orders:
        order_dict = {
            "id": order.id,
            "spot_id": order.spot_id,
            "quantity": order.quantity,
            "total_price": order.total_price,
            "status": order.status,
            "visit_date": format_datetime(order.visit_date),
            "contact_name": order.contact_name,
            "contact_phone": order.contact_phone,
            "created_at": format_datetime(order.created_at),
            "expires_at": format_datetime(order.expires_at),
            "rating": order.rating,
            "comment": order.comment,
            "commented_at": format_datetime(order.commented_at),
            "is_anonymous": order.is_anonymous,
            "spot": {
                "id": order.spot.id,
                "name": order.spot.name,
                "price": order.spot.price,
                "images": order.spot.images
            }
        }
        result.append(order_dict)
    
    return result

@router.post("")
def create_order(
    order_data: dict,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """创建订单"""
    spot = db.query(Spot).filter(Spot.id == order_data["spot_id"]).first()
    if not spot:
        raise HTTPException(status_code=404, detail="景点不存在")
    
    if spot.inventory < order_data["quantity"]:
        raise HTTPException(status_code=400, detail="库存不足")
    
    # 使用北京时间
    beijing_tz = timezone('Asia/Shanghai')
    now = datetime.now(beijing_tz)
    expires_at = now + timedelta(minutes=30)
    
    order = Order(
        user_id=current_user.id,
        spot_id=order_data["spot_id"],
        quantity=order_data["quantity"],
        total_price=order_data["total_price"],
        status="pending",
        visit_date=order_data["visit_date"],
        contact_name=order_data["contact_name"],
        contact_phone=order_data["contact_phone"],
        created_at=now,
        expires_at=expires_at
    )
    
    try:
        # 扣减库存
        spot.inventory -= order_data["quantity"]
        
        db.add(order)
        db.commit()
        db.refresh(order)
        
        return {
            "message": "订单创建成功，请在30分钟内完成支付，否则订单将自动取消",
            "order_id": order.id,
            "expires_at": expires_at.isoformat()
        }
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=400, detail=str(e))

@router.post("/{order_id}/pay")
def pay_order(
    order_id: int,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """支付订单（模拟支付）"""
    order = (
        db.query(Order)
        .filter(Order.id == order_id, Order.user_id == current_user.id)
        .first()
    )
    
    if not order:
        raise HTTPException(status_code=404, detail="订单不存在")
        
    if order.status != "pending":
        raise HTTPException(status_code=400, detail="订单状态不正确")
    
    # 直接将订单标记为已支付
    order.status = "paid"
    db.commit()
    db.refresh(order)
    
    return {"message": "支付成功"}

@router.post("/{order_id}/cancel")
def cancel_order(
    order_id: int,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """取消订单"""
    order = (
        db.query(Order)
        .filter(Order.id == order_id, Order.user_id == current_user.id)
        .first()
    )
    
    if not order:
        raise HTTPException(status_code=404, detail="订单不存在")
        
    if order.status != "pending":
        raise HTTPException(status_code=400, detail="只能取消待支付的订单")
    
    # 恢复库存
    spot = db.query(Spot).filter(Spot.id == order.spot_id).first()
    spot.inventory += order.quantity
    
    # 取消订单
    order.status = "cancelled"
    db.commit()
    
    return {"message": "订单已取消"}

@router.get("/{order_id}")
def get_order(
    order_id: int,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """获取订单详情"""
    order = (
        db.query(Order)
        .filter(Order.id == order_id, Order.user_id == current_user.id)
        .join(Spot)
        .options(joinedload(Order.spot))
        .first()
    )
    
    if not order:
        raise HTTPException(status_code=404, detail="订单不存在")
    
    # 转换为北京时间
    beijing_tz = timezone('Asia/Shanghai')
    
    def format_datetime(dt):
        if dt:
            # 如果时间没有时区信息，假定为本地时间
            if dt.tzinfo is None:
                beijing_tz = timezone('Asia/Shanghai')
                dt = beijing_tz.localize(dt)
            # 确保时间是北京时间
            beijing_time = dt.astimezone(timezone('Asia/Shanghai'))
            # 返回格式化的时间字符串
            return beijing_time.strftime('%Y-%m-%d %H:%M:%S')
        return None
    
    return {
        "id": order.id,
        "spot_id": order.spot_id,
        "quantity": order.quantity,
        "total_price": order.total_price,
        "status": order.status,
        "visit_date": format_datetime(order.visit_date),
        "contact_name": order.contact_name,
        "contact_phone": order.contact_phone,
        "created_at": format_datetime(order.created_at),
        "expires_at": format_datetime(order.expires_at),
        "rating": order.rating,
        "comment": order.comment,
        "commented_at": format_datetime(order.commented_at),
        "is_anonymous": order.is_anonymous,
        "spot": {
            "id": order.spot.id,
            "name": order.spot.name,
            "price": order.spot.price,
            "images": order.spot.images
        }
    }

@router.post("/{order_id}/review")
def review_order(
    order_id: int,
    review: dict,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """评价或修改评价"""
    order = (
        db.query(Order)
        .filter(Order.id == order_id, Order.user_id == current_user.id)
        .first()
    )
    
    if not order:
        raise HTTPException(status_code=404, detail="订单不存在")
        
    if order.status != "paid":
        raise HTTPException(
            status_code=400, 
            detail=f"只能评价已支付的订单，当前状态: {order.status}"
        )
    
    # 验证评分范围
    if not 1 <= review["rating"] <= 5:
        raise HTTPException(
            status_code=400,
            detail="评分必须在1-5之间"
        )
    
    # 验证评价内容
    if not review.get("comment"):
        raise HTTPException(
            status_code=400,
            detail="评价内容不能为空"
        )
    
    # 更新订单评价信息
    order.rating = review["rating"]
    order.comment = review["comment"]
    order.is_anonymous = review.get("is_anonymous", False)
    order.commented_at = datetime.now(timezone('Asia/Shanghai'))
    
    # 更新景点的平均评分
    spot = db.query(Spot).filter(Spot.id == order.spot_id).first()
    if spot:
        all_ratings = [
            o.rating for o in db.query(Order.rating)
            .filter(
                Order.spot_id == spot.id,
                Order.rating.isnot(None)
            ).all()
        ]
        # 添加当前评分
        all_ratings.append(review["rating"])
        # 计算平均分
        spot.rating = sum(all_ratings) / len(all_ratings)
    
    try:
        db.commit()
        return {"message": "评价成功"}
    except Exception as e:
        db.rollback()
        raise HTTPException(
            status_code=500,
            detail=f"保存评价失败: {str(e)}"
        )

@router.delete("/{order_id}/review")
def delete_review(
    order_id: int,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """删除评价"""
    order = (
        db.query(Order)
        .filter(Order.id == order_id, Order.user_id == current_user.id)
        .first()
    )
    
    if not order:
        raise HTTPException(status_code=404, detail="订单不存在")
        
    if not order.rating:
        raise HTTPException(status_code=400, detail="订单未评价")
    
    # 清除评价信息
    order.rating = None
    order.comment = None
    order.commented_at = None
    order.is_anonymous = False
    
    # 重新计算景点评分
    spot = db.query(Spot).filter(Spot.id == order.spot_id).first()
    if spot:
        ratings = [
            o.rating for o in db.query(Order.rating)
            .filter(
                Order.spot_id == spot.id,
                Order.rating.isnot(None)
            ).all()
        ]
        spot.rating = sum(ratings) / len(ratings) if ratings else 0
    
    db.commit()
    return {"message": "评价已删除"}

@router.delete("/{order_id}")
def delete_order(
    order_id: int,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """删除订单"""
    order = (
        db.query(Order)
        .filter(Order.id == order_id, Order.user_id == current_user.id)
        .first()
    )
    
    if not order:
        raise HTTPException(status_code=404, detail="订单不存在")
        
    if order.status not in ['cancelled', 'paid']:
        raise HTTPException(status_code=400, detail="只能删除已取消或已支付的订单")
    
    # 如果订单有评价，需要重新计算景点评分
    if order.rating:
        spot = db.query(Spot).filter(Spot.id == order.spot_id).first()
        if spot:
            ratings = [
                o.rating for o in db.query(Order.rating)
                .filter(
                    Order.spot_id == spot.id,
                    Order.rating.isnot(None),
                    Order.id != order_id
                ).all()
            ]
            spot.rating = sum(ratings) / len(ratings) if ratings else 0
    
    db.delete(order)
    db.commit()
    
    return {"message": "订单已删除"} 